﻿using CBS.APP;
using CBS.Common.Office;
using CBS.Model.ManageModel;
using CBS.Model.UIModel;
using CBS.Model.ViewModel;
using Microsoft.Win32;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CBS.Desktop.SystemStatement
{
    /// <summary>
    /// TeacherPaybackStatement.xaml 的交互逻辑
    /// </summary>
    public partial class TeacherPaybackStatement : Window
    {
        private Pagination pager = new() { rows = 10, page = 1, sidx = nameof(CourseBillingStatementViewModel.StudentId), sord = "desc" };
        public TeacherPaybackStatement()
        {
            InitializeComponent();

            LoadCondation();
        }

        private async void LoadCondation()
        {
            btn_Search.IsEnabled = false;
            btn_Export.IsEnabled = false;

            // 加载 ComboBox 数据
            await LoadDataAsync();

            // 查询 Grid 数据
            //FlushGrid();

            btn_Search.IsEnabled = true;
            btn_Export.IsEnabled = true;
        }

        private async Task LoadDataAsync()
        {
            // 使用 Task.WhenAll 等待所有 ComboBox 数据加载完成
            var tasks = new List<Task>
            {
                BindSemester(),
                BindClass(),
            };

            await Task.WhenAll(tasks);
        }

        private async void FlushGrid()
        {
            btn_Search.IsEnabled = false;
            btn_Export.IsEnabled = false;
            int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
            int classPlanId = int.Parse(cb_Class.SelectedValue.ToString()); ;
            string studentName = tb_Student.Text.Trim();
            var data = await Task.Run(() => SystemStatementApp.GetTeacherPaybackStatementList(pager, semesterId, classPlanId, studentName));

            this.Dispatcher.Invoke(new Action(() =>
            {
                pg_DataList.MaxPageCount = pager.total;
                dg_Data.ItemsSource = data;
                btn_Search.IsEnabled = true;
                btn_Export.IsEnabled = true;
            }));
        }

        public async Task BindSemester()
        {
            btn_Search.IsEnabled = false;
            btn_Export.IsEnabled = false;
            var list = await Task.Run(() => SemesterApp.GetSelectList());


            this.Dispatcher.Invoke(() =>
            {
                cb_Semester.ItemsSource = list;
            });
            cb_Semester.SelectedIndex = 0;

        }

        public async Task BindClass()
        {
            btn_Search.IsEnabled = false;
            btn_Export.IsEnabled = false;
            int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
            var list = await Task.Run(() => ClassApp.GetSelectList());

            list.Insert(0, new() { ClassId = 0, ClassName = "全部" });

            this.Dispatcher.Invoke(new Action(() =>
            {
                cb_Semester.ItemsSource = list;
            }));
            cb_Semester.SelectedIndex = 0;

            FlushGrid();
        }

        private void btn_Search_Click(object sender, RoutedEventArgs e)
        {
            pager.page = 1;
            pg_DataList.PageIndex = 1;
            FlushGrid();
        }

        private void btn_Export_Click(object sender, RoutedEventArgs e)
        {
            btn_Search.IsEnabled = false;
            btn_Export.IsEnabled = false;
            Mouse.OverrideCursor = Cursors.Wait;


            OpenFolderDialog dialog = new OpenFolderDialog();
            var result = dialog.ShowDialog();
            if (result == true)
            {
                ExportToFile(dialog.FolderName);
            }


            btn_Search.IsEnabled = true;
            btn_Export.IsEnabled = true;
            Mouse.OverrideCursor = null;

        }

        private async void ExportToFile(string filePath)
        {
            int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
            int classPlanId = int.Parse(cb_Class.SelectedValue.ToString()); ;
            string studentName = tb_Student.Text.Trim();
            var data = await Task.Run(() => SystemStatementApp.GetTeacherPaybackStatementDataTable(semesterId, classPlanId, studentName));

            string fileName = $"{filePath}\\学生签到详情报表-{new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()}.xlsx";
            List<ImportField> fields = new()
            {
                new(){ Name = "SemesterName", DisplayName = "学期名称" },
                new(){ Name = "ClassPlanName", DisplayName = "班级名称" },
                new(){ Name = "ClassPlanName", DisplayName = "班级名称" },
                new(){ Name = "TeacherName", DisplayName = "讲课老师" },
                new(){ Name = "StudentName", DisplayName = "学生姓名" },
                new(){ Name = "StartTime", DisplayName = "开始时间" },
                new(){ Name = "IsTaster", DisplayName = "是否是试听课" },
            };

            string[] nameArray = fields.Select(t => t.Name).ToArray();
            foreach (DataColumn col in data.Columns)
            {
                var field = fields.FirstOrDefault(t => t.Name == col.ColumnName);
                if (field == null)
                {
                    data.Columns.Remove(col);
                    continue;
                }

                col.Caption = field.DisplayName;
            }

            ExcelHelper.TableToExcelForXLSX(data, $"{filePath}\\{fileName}");

            btn_Search.IsEnabled = true;
            btn_Export.IsEnabled = true;
        }

        private void pg_DataList_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            pager.page = e.Info;
            FlushGrid();
        }
    }
}
